package com.archermind.boc.xml.converter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class HashMapConverter implements Converter {
	public boolean canConvert(Class clazz) {
		return clazz.equals(HashMap.class);
	}

	@SuppressWarnings("unchecked")
	public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
		HashMap<String, List<String>> map = (HashMap<String, List<String>>) value;
		for (Entry<String, List<String>> en : map.entrySet()) {
			String name = en.getKey();
			for (String nodeValue : en.getValue()) {
				writer.startNode(name);
				writer.setValue(nodeValue);
				writer.endNode();
			}
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		HashMap<String, List<String>> map = new HashMap<String, List<String>>();
		while (reader.hasMoreChildren()) {
			reader.moveDown();
			String name = reader.getNodeName();
			String value = reader.getValue();
			if (map.containsKey(name))
				map.get(name).add(value);
			else {
				List<String> list = new ArrayList<String>();
				list.add(value);
				map.put(name, list);
			}
			reader.moveUp();
		}
		return map;
	}
}
